#####################
#
# Figure 2: Number of Boko Haram Events, 2009-2018
# Date : 2025-02-04 (first vers. 2021-06-16)
#
#######################

output_version <- Sys.Date()

adm0_lake_chad_shp = paste0(wkdir,'/local/gis_data/003_boundaries/lake_chad/lake_chad_adm0')
adm0_reg_sf <- read_sf(dirname(adm0_lake_chad_shp), basename(adm0_lake_chad_shp))

##
## downloaded ACLED 2020-04-01
##
acled.df <- readxl::read_excel(paste0(wkdir,'/local/tab_data/Africa_1997-2020_Mar28-1.xlsx'))
conf.df <- subset(acled.df,COUNTRY %in% c('Nigeria','Cameroon','Chad','Niger'))

boko <- c('Islamic State (West Africa) and/or Boko Haram - Jamatu Ahli is-Sunnah lid-Dawatai wal-Jihad','Boko Haram - Jamatu Ahli is-Sunnah lid-Dawatai wal-Jihad')
conf.df <- subset(conf.df, ACTOR1 %in% boko | ACTOR2 %in% boko)

conf.df$COMBINED_EVENT_FATAL = conf.df$FATALITIES 
conf.df$COMBINED_EVENT_FATAL[conf.df$COMBINED_EVENT_FATAL==0] = 0.5

minyear = 2009
maxyear = 2018
conf.df <- subset(conf.df,YEAR %in% minyear:maxyear)

geoCRS <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"

conf.spdf <- st_as_sf(conf.df, coords = c("LONGITUDE", "LATITUDE"), crs = geoCRS) 
conf.spdf$event <- 1
conf.spdf$EVENT_DATE = as.Date(conf.spdf$EVENT_DATE)
conf.spdf$month = as.integer(format(conf.spdf$EVENT_DATE,"%m"))

##
## bar plot by country
##

conf.spdf = conf.spdf %>%
  mutate(grouping = ifelse((YEAR >=2009 & YEAR <=2013), "Period of Analysis","After Period of Analysis"))

conf.spdf <- conf.spdf %>% mutate(grouping = factor(grouping, levels = c("Period of Analysis", "After Period of Analysis"))) 

##
## NUMBER OF EVENTS
##

event_stacked_bar <- ggplot(conf.spdf %>% count(COUNTRY, YEAR, grouping) %>%    # Group by count and year, then count number in each group
         mutate(pct=n/sum(n),               # Calculate percent within each region
                ypos = cumsum(n) - 0.5*n),  # Calculate label positions
       aes(YEAR, n, fill=COUNTRY)) +
 
  scale_fill_manual(values = c("grey35","grey55","grey85","grey5"))+
  geom_bar(position = "stack",stat="identity") +
  theme_bw() +
  ylab("Number of events") +
  scale_x_continuous(name="Year", breaks=c(minyear:maxyear))+ 
  
  facet_grid(~grouping, switch = "x", scales = "free_x", space = "free_x") +
  theme(panel.spacing = unit(0, "lines"), 
        strip.background = element_blank(),
        strip.placement = "outside") + 
  xlab("Year")

ggsave(event_stacked_bar, filename=paste0(figdir,'/boko_haram_events_stackedbar',minyear,'-',maxyear,'.png'))
